import markdown
from django.db.models import Q
from django.shortcuts import get_object_or_404, render
from mdeditor.fields import MDTextField

from oa.views import AppDetailView, AppListView, PermissionRequireTemplateView
from sop.models import SopDocument


def md_content(model, obj):
    # 渲染 Markdown 文件
    fs = getattr(model, '_meta').fields
    content = list()
    section_index = 1
    for f in fs:
        if isinstance(f, MDTextField):
            if getattr(obj, f.name):
                section_body = markdown.markdown(
                    getattr(obj, f.name),
                    extensions=[
                        'markdown.extensions.extra',
                        'markdown.extensions.codehilite',
                        'markdown.extensions.toc',
                        'markdown.extensions.nl2br',
                        'markdown.extensions.admonition',
                        'markdown.extensions.codehilite',
                        'markdown.extensions.legacy_attrs',
                        'markdown.extensions.sane_lists',
                        'markdown.extensions.smarty',
                        'markdown.extensions.wikilinks'
                    ])
                content.append(
                    {
                        'section_index': section_index,
                        'section_name': f.verbose_name,
                        'section_body': section_body,
                    })
                section_index += 1
    return content


class DocView(AppDetailView):
    template_name = 'sop/document.html'
    model = SopDocument

    def get(self, request, *args, **kwargs):
        obj = get_object_or_404(self.model, pk=kwargs.get('pk'))
        content = md_content(self.model, obj)  # 渲染 Markdown 文件
        return render(request, self.template_name, context={'doc': {'obj': obj, 'content': content}})


class DocListView(AppListView):
    model = SopDocument
    queryset = SopDocument.objects.filter(current_active=True).order_by('code')
    template_name = 'sop/document_list.html'
    permission_denied_message = '权限不够，找老板'
    paginate_by = 20
    list_filter = ['department', 'version_code', 'document_level', 'document_type']
    search_fields = ['name', 'code']

    def get_queryset(self):
        queryset = super().get_queryset()
        q = self.request.GET.get('q')
        if q:
            queryset = queryset.filter(Q(name__icontains=q) | Q(code__icontains=q)).distinct()
        return queryset


class DocAllView(PermissionRequireTemplateView):
    template_name = 'sop/document_all.html'
    permission_denied_message = '权限不够，找老板'
    permission_required = []

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        docs = list()
        queryset = SopDocument.objects.filter(current_active=True).order_by('document_type', 'department', 'code')
        for c in queryset:
            content = md_content(SopDocument, c)
            docs.append({'obj': c, 'content': content})
        context['docs'] = docs
        return context
